import {
  getApps
} from '.'

import {
  importHtml
} from './import-html'

import { getPrevRoute, getNextRoute } from './rewite-router'
export const handleRouter = async () => {
  // 卸载上一个应用

  // 2. 匹配子应用
  const apps = getApps()
  const prevApp = apps.find(item => {
    return getPrevRoute().startsWith(item.activeRule)
  })
  const app = apps.find(item => getNextRoute().startsWith(item.activeRule))
  //   const app = apps.find(item => window.location.pathname.startsWith(item.activeRule))
  if (prevApp) {
    await unmount(prevApp)
  }

  if (!app) return false

  // 3. 加载子应用
  const container = document.querySelector(app.container)
  const {
    template,
    // getExternalScripts
    execScropts
  } = await importHtml(app.entry)
  container.appendChild(template)
  window.__POWERED_BY_QIANKUN__ = true
  window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ = app.entry + '/'
  const appExport = await execScropts()
  console.log(appExport)

  app.bootstrap = appExport.bootstrap
  app.mount = appExport.mount
  app.unmount = appExport.unmount
  await bootstrap(app)
  await mount(app)
  //   getExternalScripts().then(srcipt => {
  //     console.log(srcipt)
  //   })
  //  手动执行srcipt的代码
  //   import-html-entry

  // 4. 渲染子应用
}

async function bootstrap (app) {
  app.bootstrap && (await app.bootstrap())
}

async function mount (app) {
  app.mount && (await app.mount({
    container: document.querySelector(app.container)
  }))
}

async function unmount (app) {
  app.unmount && (await app.unmount({
    container: document.querySelector(app.container)
  }))
}
